import { Server } from "socket.io";
import { nanoid } from "nanoid";
 import { createToken } from './modules/createToken.js'
import dotenv from 'dotenv'
dotenv.config()
console.log(process.env.NODE_ENV);
const io = new Server({
  cors: true,
});
const users = [];
io.use((socket, next) => {
  const userId = socket.handshake.auth.userId;
  if (userId) {
    const user = users.find((user) => user.userId === userId);
    if (!user) {
      return next(new Error("invalid userId"));
    }
    socket.userId = user.userId;
    socket.username = user.username;
    return next();
  }
  const username = socket.handshake.auth.username;
  if (!username) {
    return next(new Error("invalid username"));
  }
  if (users.find((user) => user.username === username)) {
    return next(new Error("username already taken"));
  }
  socket.username = username;
  socket.userId = nanoid();
  next();
});
io.on("connection", (socket) => {
  console.log('connection');
  const username = socket.username;
  const userId = socket.userId;
  socket.join(userId);
  const findRes = users.find((user) => user.userId === userId);
  if (!findRes) {
    users.push({ userId, username, message: [], onLine: true });
    io.to(userId).emit("session", { userId, username });
  } else {
    findRes.onLine = true;
  }
  io.emit("users", users);
  // 发送消息
  socket.on("send-message", ({ toId, message }) => {
    io.to(toId)
      .to(userId)
      .emit("receive-message", { message, userId, username, toId });
  });
  // 通话
  socket.on("call", async ({ toId }) => {
    const startToken = await createToken({roomName:userId,participantName:userId})
    const joinToken = await createToken({roomName:userId,participantName:toId})
    io.to(toId).emit("join", { token:joinToken});
    io.to(userId).emit("createCall", { token:startToken});
  });
  // 断开连接
  socket.on("disconnect", () => {
    const findUserItem = users.find((user) => user.userId === userId);
    if (findUserItem) {
      findUserItem.onLine = false;
    }
    io.emit("users", users);  
  });
});
io.listen(3000);
